//
//  KSKALineChart.m
//  DashboardHD
//
//  Created by 楊亜玲 on 17/3/28.
//  Copyright © 2017年 Totyu. All rights reserved.
//

#define DLineY(stri) (_YMaxLength - [(stri) floatValue]) / (_YTotalLength/(self.height - 2)) + 1
#define LineX(stri) (stri) * (self.width / _XTotalLength)
#define LineWidth 1
#define GuidelineWidth 0.3
#define LabelHeight 10
#define LabelWidth 60
#define GuidelineColor [UIColor blackColor]

#import "KSKALineChart.h"

@interface KSKALineChart ()


@property (nonatomic, assign) float YMaxLength; // y坐标最大值
@property (nonatomic, assign) float YMinLength; // y坐标最小值
@property (nonatomic, assign) int XTotalLength; // x坐标段数
@property (nonatomic, assign) float YTotalLength; // y坐标段数

@property(nonatomic, strong) KSKAKatsudouResult *result;
/** 图表种类(环境／活动) */
@property(nonatomic, assign) eventType type;
/** 活动分类 */
@property(nonatomic, strong) NSString *actionid;

@end

@implementation KSKALineChart

-(instancetype)initWithFrame:(CGRect)frame dataSource:(KSKAKatsudouResult *)dataSource eventType:(eventType)type{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [[UIColor lightGrayColor]colorWithAlphaComponent:0.2];
        self.result = dataSource;
        self.type = type;
        self.actionid = _result.actionid;
        
        [self setupFrameData];

    }
    return self;
}


-(void)drawRect:(CGRect)rect{
    // 1.绘制折线
    NSString *colorHex = _result.actioncolor;
    if (_type  == eventTypeEviroment) {    // 温度、湿度
        [self drawChartLine:_result.avg lineColor:colorHex dottedLineBOOL:YES];
        [self drawChartLine:_result.max lineColor:colorHex dottedLineBOOL:NO];
        [self drawChartLine:_result.min lineColor:colorHex dottedLineBOOL:NO];
    }else{    //　活動
        [self drawChartLine:_result.data lineColor:colorHex dottedLineBOOL:NO];
    }
    
    // 2.绘制辅助线
    [self settingGuidelines];
    
    // 3.添加最大，最小值label
    [self AddMaxAndMinLabel];
    
}


/** 计算 */
-(void)setupFrameData{
    
    // x,y坐标相关计算
    if ([_actionid isEqualToString:@"環境1"]) {
        _XTotalLength = (int)_result.avg.count - 1;
        _YMaxLength = 50;
        _YMinLength = 0;
    }else if ([_actionid isEqualToString:@"環境2"]){
        _XTotalLength = (int)_result.avg.count - 1;
        
        _YMaxLength = 100;
        _YMinLength = 0;
    }else{
        _XTotalLength = (int)_result.data.count - 1;
        
        NSArray *tmpArr = [self filterArrayFromNumberArray:_result.data];
        _YMaxLength = [[tmpArr valueForKeyPath:@"@max.floatValue"] floatValue];
        _YMinLength = [[tmpArr valueForKeyPath:@"@min.floatValue"] floatValue];
    }
    _YTotalLength = _YMaxLength - _YMinLength;
    
}

#pragma mark - 划线方法
/**
 绘制折线

 @param lineArray 折线点的数组
 @param colorHexStr 颜色字符串
 @param dottedLineBOOL 是否虚线
 */
-(void)drawChartLine:(NSArray*)lineArray lineColor:(NSString *)colorHexStr dottedLineBOOL:(BOOL)dottedLineBOOL{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, LineWidth);
    [[UIColor colorWithHex:colorHexStr] setStroke];
    // 是否是虚线虚线
    if (dottedLineBOOL) {
        CGFloat arr[] = {3,1};
        CGContextSetLineDash(context, 0, arr, 2);
    }
    if (lineArray.count > 0 ) {
        NSArray *dataArr = [self stringArrayFromNumberArray:lineArray];
        [dataArr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            if (idx < dataArr.count-1) {//前后空数据判断
                if (![obj isEqualToString:@""]&&![dataArr[idx+1] isEqualToString:@""]) {
                    CGContextMoveToPoint(context, LineX(idx), DLineY(obj));
                    CGContextAddLineToPoint(context, LineX(idx+1), DLineY(dataArr[idx+1]));
                    NSLog(@"%f %f %f %f",LineX(idx),DLineY(obj),LineX(idx+1),DLineY(dataArr[idx+1]));
                    CGContextDrawPath(context, kCGPathStroke);
                }
            }
        }];
    }
}


/** 绘制辅助线 */
-(void)settingGuidelines{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, GuidelineWidth);
    [GuidelineColor setStroke];
    CGFloat arr[] = {2,1};
    CGContextSetLineDash(context, 0, arr, 2);
    int total;
    //if (_LineType == EnvironmentList) {
    //total = 24;
    //} else {
    total = _XTotalLength;
    //}
    for (int i = 0; i <= total; i++) {
        if (i > 0 && i < total) {
            CGContextMoveToPoint(context, self.width / total * i, self.height);
            CGContextAddLineToPoint(context, self.width / total * i, 0);
        }
    }
    CGContextDrawPath(context, kCGPathStroke);
}

#pragma mark - 添加辅助子控件

/** 添加最大值，最小值label */
-(void)AddMaxAndMinLabel{
    NSDictionary *NumAttrs = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:9], NSFontAttributeName, [UIColor blackColor], NSForegroundColorAttributeName, nil];
    NSString *maxStr = [NSString stringWithFormat:@"Max:%0.2f",_YMaxLength];
    NSString *minStr = [NSString stringWithFormat:@"Min:%0.2f",_YMinLength];
    [maxStr drawInRect:CGRectMake(2, 0, LabelWidth, LabelHeight) withAttributes:NumAttrs];
    [minStr drawInRect:CGRectMake(2, self.height - LabelHeight, LabelWidth, LabelHeight) withAttributes:NumAttrs];
    
}

#pragma mark - 数据处理
/** 过滤数组（只保留有值的） */
-(NSArray *)filterArrayFromNumberArray:(NSArray *)numArray{
    NSMutableArray *result = [NSMutableArray array];
    for (int i = 0; i < numArray.count; i ++) {
        NSNumber *num = [numArray objectAtIndex:i];
        if (![num isKindOfClass:[NSNull class]]) {
            NSString *str = [NSString stringWithFormat:@"%@",num];
            [result addObject:str];
        }
    }
    return result;
}

/** 过滤数组（空值 设为空 字符串） */
-(NSArray *)stringArrayFromNumberArray:(NSArray *)numArray{
    NSMutableArray *result = [NSMutableArray array];
    for (int i = 0; i < numArray.count; i ++) {
        NSString *str =@"";
        NSNumber *num = [numArray objectAtIndex:i];
        if (![num isKindOfClass:[NSNull class]]) {
            str = [NSString stringWithFormat:@"%@",num];
        }
        [result addObject:str];
    }
    return result;
}

@end
